import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useNavigate, useLocation } from 'react-router-dom';
import { Table, Select, Button, DatePicker, Form, Row, Col, Card, Modal, Input, message, Space, Tag } from 'antd';
import { ExportOutlined, DeleteOutlined, CheckCircleOutlined, ClockCircleOutlined, PlayCircleOutlined, PlusOutlined } from '@ant-design/icons';
import './ProjectList.css';
import {
  EyeOutlined,
  FileTextOutlined,
  UserOutlined,
  TeamOutlined,
  FileDoneOutlined,
} from "@ant-design/icons";
import { get, post } from '../../components/axios';

const { Option } = Select;

export default function ProjectList() {
  const navigate = useNavigate();
  const location = useLocation();
  // 弹窗相关状态
  const [pauseModalVisible, setPauseModalVisible] = useState(false);
  const [restartModalVisible, setRestartModalVisible] = useState(false);
  const [pauseReason, setPauseReason] = useState('');
  const [restartTime, setRestartTime] = useState(null);
  const [currentPhase, setCurrentPhase] = useState('产品部阶段');
  const [dataSource, setDataSource] = useState([]);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [loading, setLoading] = useState(false);
  const [newProjectId, setNewProjectId] = useState(null);

  // const [dataSource, setDataSource] = useState([]);
  // ... 其它state ...

  // 查询
  const fetchData = (params = {}) => {
    setLoading(true);
    post('/projectlist/search', params).then(res => {
      console.log('后端返回：', res.data);
      if (res.data && res.data.data) {
        setDataSource(res.data.data.list || []);
        setPagination(prev => ({
          ...prev,
          current: params.page || 1,
          pageSize: params.pageSize || 10,
          total: res.data.data.total || 0
        }));
      }
      setLoading(false);
    }).catch((err) => {
      console.error('获取数据失败:', err);
      setLoading(false);
    });
  };

  useEffect(() => {
    fetchData({ page: 1, pageSize: 10 });
  }, [location.state]);

  // 监听location.state变化，如果有refresh状态则刷新数据
  useEffect(() => {
    if (location.state?.refresh) {
      // 如果有新添加的项目数据，将其添加到列表顶部
      if (location.state?.newProject) {
        setDataSource(prevData => {
          // 检查是否已经存在相同ID的项目，避免重复
          const exists = prevData.find(item => item._id === location.state.newProject._id);
          if (exists) {
            return prevData;
          }
          return [location.state.newProject, ...prevData];
        });
        setPagination(prev => ({
          ...prev,
          total: prev.total + 1
        }));
        
        // 设置新项目ID用于高亮显示
        setNewProjectId(location.state.newProject._id);
        
        // 3秒后清除高亮状态
        setTimeout(() => {
          setNewProjectId(null);
        }, 3000);
      } else {
        // 否则重新获取数据
        fetchData({ page: 1, pageSize: 10 });
      }
      // 清除状态，避免重复刷新
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  const handleSearch = () => {
    form.validateFields().then(values => {
      // 处理日期范围
      let searchParams = { ...values };
      if (values.creationTime && values.creationTime.length === 2) {
        searchParams.creationTime = [
          values.creationTime[0].format('YYYY-MM-DD'),
          values.creationTime[1].format('YYYY-MM-DD')
        ];
      }
      
      // 过滤掉空字符串、null、undefined 字段
      const cleanParams = Object.fromEntries(
        Object.entries(searchParams).filter(([_, v]) => {
          if (v === undefined || v === null || v === '') return false;
          if (Array.isArray(v) && v.length === 0) return false;
          return true;
        })
      );
      
      console.log('搜索参数:', cleanParams);
      fetchData({ ...cleanParams, page: 1, pageSize: pagination.pageSize });
    });
  };

  const handleReset = () => {
    form.resetFields();
    fetchData({ page: 1, pageSize: pagination.pageSize });
  };

  const handleTableChange = (pag) => {
    form.validateFields().then(values => {
      // 处理日期范围
      let searchParams = { ...values };
      if (values.creationTime && values.creationTime.length === 2) {
        searchParams.creationTime = [
          values.creationTime[0].format('YYYY-MM-DD'),
          values.creationTime[1].format('YYYY-MM-DD')
        ];
      }
      
      // 过滤掉空字符串、null、undefined 字段
      const cleanParams = Object.fromEntries(
        Object.entries(searchParams).filter(([_, v]) => {
          if (v === undefined || v === null || v === '') return false;
          if (Array.isArray(v) && v.length === 0) return false;
          return true;
        })
      );
      
      fetchData({ ...cleanParams, page: pag.current, pageSize: pag.pageSize });
    });
  };

  // 删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除该项目？',
      onOk: () => {
        post('/projectlist/delete', { id: record._id }).then((res) => {
          if (res?.data?.code === 200 || res?.code === 200) {
            message.success('删除成功');
            // 刷新列表数据
            fetchData({ page: pagination.current, pageSize: pagination.pageSize });
          } else {
            message.error(res?.data?.msg || res?.msg || '删除失败');
          }
        }).catch((err) => {
          message.error('删除失败');
          console.error('删除出错:', err);
        });
      }
    });
  };

  // 弹窗触发函数
  const handlePauseClick = (record) => {
    setCurrentPhase(record.projectName || '产品部阶段');
    setPauseModalVisible(true);
  };
  const handleRestartClick = (record) => {
    setCurrentPhase(record.projectName || '产品部阶段');
    setRestartModalVisible(true);
  };

  // 弹窗内容
  const PauseModal = (
    <Modal
      open={pauseModalVisible}
      onCancel={() => setPauseModalVisible(false)}
      footer={null}
      width={400}
      centered
      closable={false}
      styles={{ body: { padding: 0, background: '#fff' }, mask: { background: 'rgba(100,120,140,0.6)' } }}
      style={{ top: 80 }}
    >
      <div style={{ background: '#0a2940', color: '#fff', padding: '12px 24px', fontWeight: 600, fontSize: 16, borderTopLeftRadius: 4, borderTopRightRadius: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        填写暂停原因
        <span style={{ cursor: 'pointer', fontSize: 18 }} onClick={() => setPauseModalVisible(false)}>×</span>
      </div>
      <div style={{ padding: 32, paddingTop: 24 }}>
        <div style={{ marginBottom: 16 }}>
          <span style={{ color: '#888' }}>当前阶段：</span>
          <span>{currentPhase}</span>
        </div>
        <div style={{ marginBottom: 16 }}>
          <span style={{ color: 'red', marginRight: 4 }}>*</span>
          <span>暂停原因：</span>
          <Input.TextArea
            value={pauseReason}
            onChange={e => setPauseReason(e.target.value)}
            placeholder="请输入"
            rows={5}
            style={{ marginTop: 8 }}
          />
        </div>
        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <Button type="primary" style={{ marginRight: 16, width: 80 }} onClick={() => setPauseModalVisible(false)}>保存</Button>
          <Button style={{ width: 80 }} onClick={() => setPauseModalVisible(false)}>取消</Button>
        </div>
      </div>
    </Modal>
  );

  const RestartModal = (
    <Modal
      open={restartModalVisible}
      onCancel={() => setRestartModalVisible(false)}
      footer={null}
      width={400}
      centered
      closable={false}
      styles={{ body: { padding: 0, background: '#fff' }, mask: { background: 'rgba(100,120,140,0.6)' } }}
      style={{ top: 80 }}
    >
      <div style={{ background: '#0a2940', color: '#fff', padding: '12px 24px', fontWeight: 600, fontSize: 16, borderTopLeftRadius: 4, borderTopRightRadius: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        选择重启时间
        <span style={{ cursor: 'pointer', fontSize: 18 }} onClick={() => setRestartModalVisible(false)}>×</span>
      </div>
      <div style={{ padding: 32, paddingTop: 24 }}>
        <div style={{ marginBottom: 16 }}>
          <span style={{ color: 'red', marginRight: 4 }}>*</span>
          <span>从启用时间：</span>
          <DatePicker
            value={restartTime}
            onChange={setRestartTime}
            placeholder="请选择"
            style={{ width: 220, marginLeft: 8 }}
          />
        </div>
        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <Button type="primary" style={{ marginRight: 16, width: 80 }} onClick={() => setRestartModalVisible(false)}>保存</Button>
          <Button style={{ width: 80 }} onClick={() => setRestartModalVisible(false)}>取消</Button>
        </div>
      </div>
    </Modal>
  );

  const columns = [
    { title: "项目状态", dataIndex: "status", align: "center" },
    // { title: "进度", dataIndex: "progress", align: "center" },
    { title: "项目编号", dataIndex: "projectNumber", align: "center" },
    { title: "项目类型", dataIndex: "projectType", align: "center" },
    { title: "合同编号", dataIndex: "contractNumber", align: "center" },
    { title: "关联客户", dataIndex: "relatedClient", align: "center" },
    { title: "项目名称", dataIndex: "projectName", align: "center" },
    { title: "签约人", dataIndex: "signatory", align: "center" },
    { title: "项目类别", dataIndex: "projectCategory", align: "center" },
    {
      title: "操作",
      key: "action",
      align: "center",
      render: (_, record) => (
        <Space size={4}>
          <Tag color="red" icon={<FileTextOutlined />} onClick={() => navigate('/projects/correspondence')}>项目函件</Tag>
          <Tag color="gray" icon={<UserOutlined />} onClick={() => navigate('/projects/phases')}>项目阶段</Tag>
          {/* <Tag color="purple" icon={<TeamOutlined />}>第三方资料</Tag> */}
          {/* <Tag color="orange" icon={<FileDoneOutlined />} onClick={() => navigate('/projects/attachment')}>项目附件</Tag> */}
          <Tag color="gold" icon={<FileDoneOutlined />} onClick={() => navigate('/projects/meetingnotes')}>会议记要</Tag>
          <Tag color="red" icon={<FileDoneOutlined />} onClick={() => navigate('/projects/aftersales')}>售后需求记录</Tag>
          {/* <Tag color="red" icon={<FileDoneOutlined />}>项目奖金记录</Tag> */}
          <Tag color="orange" icon={<EyeOutlined />} onClick={() => navigate('/projects/projectId')}>详情</Tag>
          <Button
            type="text"
            icon={<DeleteOutlined />}
            style={{ color: "#52c41a", background: "#f6ffed", border: "1px solid #d9f7be", borderRadius: 4 }}
            onClick={() => handleDelete(record)}
          />
        </Space>
      ),
    },
  ];
  return (
    <div className="project-list">
      {PauseModal}
      {RestartModal}
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <h2 style={{ margin: 0 }}>我的项目列表</h2>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/newproject')}>新建项目</Button>
          {/* <Button icon={<ExportOutlined />}>导出</Button> */}
        </Space>
      </div>

      <div className="search-bar">
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16, flexWrap: 'wrap' }}
        >
          <Form.Item label="合同编号" name="contractNumber">
            <Input placeholder="请输入合同编号" allowClear style={{ width: 150 }} />
          </Form.Item>
          <Form.Item label="签约人" name="signatory">
            <Input placeholder="请输入签约人" allowClear style={{ width: 150 }} />
          </Form.Item>
          <Form.Item label="项目状态" name="status">
            <Select placeholder="请选择" allowClear style={{ width: 120 }}>
              <Option value="未开始">未开始</Option>
              <Option value="进行中">进行中</Option>
              <Option value="已完成">已完成</Option>
              <Option value="已暂停">已暂停</Option>
            </Select>
          </Form.Item>
          <Form.Item label="项目类型" name="projectType">
            <Select placeholder="请选择" allowClear style={{ width: 120 }}>
              <Option value="外包">外包</Option>
              <Option value="Outsourcing">Outsourcing</Option>
            </Select>
          </Form.Item>
          <Form.Item label="项目分类" name="projectCategory">
            <Input placeholder="请输入项目分类" allowClear style={{ width: 150 }} />
          </Form.Item>
          {/* <Form.Item label="创建日期" name="creationTime">
            <DatePicker.RangePicker style={{ width: 200 }} />
          </Form.Item> */}
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </div>

      <div className="table-container">
        <Table
          dataSource={dataSource}
          columns={columns}
          className="project-table"
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条`,
          }}
          loading={loading}
          rowKey="_id"
          onChange={handleTableChange}
          rowClassName={(record) => {
            return record._id === newProjectId ? 'new-project-row' : '';
          }}
        />
      </div>
    </div>
  );
}